require 'mscorlib'
require 'Writespace.Dialogs'
require 'PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
require 'WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
require 'System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'

# -------- aliases -----------
Application = System::Windows::Application
WindowState = System::Windows::WindowState
MessageBox = System::Windows::MessageBox
MessageBoxButton = System::Windows::MessageBoxButton
MessageBoxResult = System::Windows::MessageBoxResult
MessageBoxImage = System::Windows::MessageBoxImage
#OpenFileDialog = System::Windows::Forms::OpenFileDialog
#DialogResult = System::Windows::Forms::DialogResult
Key = System::Windows::Input::Key
Console = System::Console
TextEditorWindow = Writespace::Dialogs::TextEditorWindow

# -------- create editor and load up file (if provided) -----------

editor = TextEditorWindow.new

if ARGV.length > 0
  content = "";
  File.open(ARGV[0], "r") do |infile|
    while (line = infile.gets)
      content = content + line
    end
  end
  editor.text = content
  editor.status = "File loaded"
end

# -------- events from editor -----------

editor.open do |sender, args|
  dialog = System::Windows::Forms::OpenFileDialog.new
  dialog.DefaultExt = "txt";
  dialog.Filter = "Text files (*.txt)|*.txt";

  result = dialog.show_dialog

  if result == System::Windows::Forms::DialogResult.OK
    filename = dialog.FileName
    content = ""
    File.open(filename, "r") do |infile|
      while (line = infile.gets)
        content = content + line
      end
    end
    editor.text = content
    editor.status = "Loaded " + filename
  end
  editor.focus
end

editor.closing do |sender, args|
  if ARGV.length > 0
    result = MessageBox.Show("Do you want to save?", "Save?", MessageBoxButton.YesNo, MessageBoxImage.Question)
    if result == MessageBoxResult.Yes
     Console.write_line "saving"
      File.open(ARGV[0], "w") do |infile|
        infile.puts(editor.text)
      end
    end
  end 
end

editor.save do |sender, args|
  if ARGV.length > 0
      File.open(ARGV[0], "w") do |infile|
      infile.puts(editor.text)
      editor.status = "Saved " + ARGV[0]
    end
  else
    dialog = System::Windows::Forms::SaveFileDialog.new
    dialog.DefaultExt = "txt";
    dialog.Filter = "Text files (*.txt)|*.txt";

    result = dialog.show_dialog

    if result == System::Windows::Forms::DialogResult.OK
      filename = dialog.FileName
      File.open(filename, "w") do |infile|
        infile.puts(editor.text)
        editor.status = "Saved " + filename
      end
    end
    editor.focus
  end
end

# -------- run as WPF app -----------
editor.WindowState = WindowState.Maximized
my_app = Application.new
my_app.run editor

